package user_v1

import (
	"context"
	"errors"
	"gf-xb-api/internal/consts"
	"gf-xb-api/internal/dao"
	"gf-xb-api/internal/model/entity"
	"gf-xb-api/internal/service"

	"github.com/gogf/gf/v2/database/gdb"
)

func (s *sUser) Disable(ctx context.Context, username string) (output bool, err error) {
	var user *entity.SysUser

	cols := dao.SysUser.Columns()

	err = dao.SysUser.Ctx(ctx).Where(cols.Username, username).Scan(&user)
	if err != nil {
		return false, err
	}

	if user == nil {
		return false, errors.New(consts.USER_NOT_FOUND)
	}

	inactive := uint(consts.USER_STATUS_INACTIVE)

	// disable user
	if user.Status == inactive {
		return true, nil
	}

	err = dao.SysUser.Transaction(ctx, func(ctx context.Context, tx gdb.TX) (err error) {

		_, err = dao.SysUser.Ctx(ctx).Data(cols.Status, inactive).WherePri(user.Id).Update()
		if err != nil {
			return err
		}

		// 将该用户的已登录实例强制登出
		err = service.User().LogoutByUuid(ctx, user.Uuid)
		if err != nil {
			return err
		}

		return nil
	})

	return true, nil
}
